/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <gtest/gtest.h>
#include "dal_rticonnextdds/converter/InstanceHandleConverter.hpp"

#define RTI_INSTANCE_HANDLE_LEN 16

static void Debug(uint8_t *buf, int len)
{
    for (int i = 0; i < len; i++) {
        printf("%X", *(buf + i));
    }
    printf("\n");
}

TEST(test_convert_instance_handle_from_rtidds_to_dal, instance_handle_convert)
{
    dal_instance_handle_t d_ins;
    DDS_InstanceHandle_t r_ins;
    d_ins.segment_0_ = 0x00112233;
    d_ins.segment_1_ = 0x44556677;
    d_ins.segment_2_ = 0;
    d_ins.segment_3_ = 0;
    dal_ret_t ret = InstanceHandleConverter::GetInstance()->ConvertInstanceHandleFromDalToRtidds(
        &d_ins, &r_ins);
    EXPECT_EQ(ret, DAL_RETCODE_OK);
    
    Debug(r_ins.keyHash.value, RTI_INSTANCE_HANDLE_LEN);
    Debug((uint8_t*)&d_ins, RTI_INSTANCE_HANDLE_LEN);
    int dif = memcmp(r_ins.keyHash.value, &d_ins, RTI_INSTANCE_HANDLE_LEN);
    EXPECT_EQ(dif, 0);
}

TEST(test_convert_instance_handle_from_dal_to_rtidds, instance_handle_convert)
{
    dal_instance_handle_t d_ins;
    DDS_InstanceHandle_t r_ins;

    uint32_t value_1 = 0x00112233;
    uint32_t value_2 = 0x44556677;
    memset(r_ins.keyHash.value, 0, RTI_INSTANCE_HANDLE_LEN);
    memcpy(r_ins.keyHash.value, &value_1, 4);
    memcpy(r_ins.keyHash.value + 4, &value_2, 4);

    dal_ret_t ret = InstanceHandleConverter::GetInstance()->ConvertInstanceHandleFromRtiddsToDal(
        &r_ins, &d_ins);

    Debug(r_ins.keyHash.value, RTI_INSTANCE_HANDLE_LEN);
    Debug((uint8_t*)&d_ins, RTI_INSTANCE_HANDLE_LEN);

    EXPECT_EQ(ret, DAL_RETCODE_OK);
    EXPECT_EQ(d_ins.segment_0_, 0x00112233);
    EXPECT_EQ(d_ins.segment_1_, 0x44556677);
    EXPECT_EQ(d_ins.segment_2_, 0);
    EXPECT_EQ(d_ins.segment_3_, 0);
}